<template>
  <div class="platform">
    <div class="top">
      <queryInput
        id="platformName"
        name="平台名称"
        :value="query.platformName"
        @update:value="handleUpdate"
      />
      <div>
        <el-button type="primary" @click="handle_query">查询</el-button>
        <el-button @click="handle_resetting">重置</el-button>
      </div>
    </div>
    <div class="cont">
      <div class="cont_top">
        <div class="total_box">
          平台总计：
          <span>{{ total }}</span>
        </div>
        <div class="operate">
          <el-button
            type="primary"
            @click="handle_drawer()"
            v-if="route.meta.add"
          >
            新建
          </el-button>
        </div>
      </div>
      <el-table
        v-loading="loading"
        style="height: 100%"
        :data="tableData"
        row-key="bm"
        :header-cell-style="{
          backgroundColor: '#f7f8fa',
          color: '#8c8c8c',
          fontWeight: 400,
          cursor: 'pointer',
        }"
        :cell-style="{ color: '#000' }"
        show-overflow-tooltip
      >
        <template #empty>
          <el-empty :image-size="100" description="暂无数据" />
        </template>
        <el-table-column type="index" label="序号" width="100" align="center">
          <template #default="scope">{{ scope.row.pid }}</template>
        </el-table-column>
        <el-table-column prop="platformName" label="平台名称" />
        <el-table-column prop="platformId" label="平台编码" />
        <el-table-column prop="organizationId" label="所属机构">
          <template #default="scope">{{
            set_institution(scope.row.organizationId)
          }}</template>
        </el-table-column>
        <el-table-column prop="platformAddress" label="平台地址">
          <template #default="scope">
            <a :href="scope.row.platformAddress" target="_blank">
              {{ scope.row.platformAddress }}
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="contactPerson" label="平台联系人" />
        <el-table-column prop="phone" label="联系人电话" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handle_drawer(scope.row)"
              v-if="route.meta.edit"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handle_del(scope.row.platformId)"
              v-if="route.meta.del"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="cont_button">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pagesize"
          :page-sizes="[15, 20, 30, 40]"
          layout="->,slot, sizes, prev, pager, next, jumper"
          :total="total"
          @change="handle_page"
        >
          <div class="total">共{{ Math.ceil(total / pagesize) }}页</div>
        </el-pagination>
      </div>
    </div>
    <!-- 新建/编辑 -->
    <el-drawer
      custom-class="drawer"
      size="36%"
      v-model="drawerVisible"
      :show-close="false"
      :with-header="false"
      :close-on-click-modal="false"
    >
      <div class="drawer_header">
        <h3>{{ drawerTitle }}</h3>
        <Close
          style="width: 20px; height: 20px; cursor: pointer"
          @click="cancel_drawer"
        />
      </div>
      <div class="drawer_cont">
        <subtitle title="基础信息" />
        <el-form
          ref="drawerForm"
          class="drawerForm"
          :model="drawerform"
          :rules="drawerRules"
          label-width="auto"
          scroll-to-error
        >
          <el-form-item label="平台名称" prop="platformName">
            <el-input v-model="drawerform.platformName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="所属机构" prop="organizationId">
            <el-tree-select
              v-model="drawerform.organizationId"
              :data="store.orgallData"
              :props="orgProps"
              :render-after-expand="false"
              check-strictly
              filterable
            />
          </el-form-item>
          <el-form-item label="平台地址" prop="platformAddress">
            <el-input
              v-model="drawerform.platformAddress"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="drawerform.contactPerson" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="drawerform.phone"
              maxlength="18"
              show-word-limit
              placeholder="请输入联系电话，建议输入11位手机号码"
              @input="
                (value) => (drawerform.phone = value.replace(/[^0-9-]/g, ''))
              "
            />
          </el-form-item>
          <div class="add_operate">
            <el-button @click="cancel_drawer">取消</el-button>
            <el-button type="primary" @click="confirm_drawer(drawerForm)">
              确认
            </el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { addSys, deleteSys, sysPage, updateSys } from "@/api/appPlatfor";
import subtitle from "@/components/subtitle.vue";
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "@/store";
import { useRoute } from "vue-router";

const store = useStore();
const route = useRoute();

const loading = ref(false);
const total = ref(0);
const page = ref(1);
const pagesize = ref(15);
const drawerVisible = ref(false);
const drawerTitle = ref("");
const drawerForm = ref(null);
const query = reactive({
  platformName: "",
});
const tableData = ref([]);
const orgProps = ref({
  children: "children",
  label: "name",
  value: "organizationid",
});
const drawerform = reactive({
  platformName: "",
  organizationId: "",
  platformAddress: "",
  contactPerson: "",
  phone: null,
  // bz: "",
});
const drawerRules = reactive({
  platformName: [
    { required: true, message: "请输入平台名称", trigger: "blur" },
  ],
  organizationId: [
    { required: true, message: "请选择所属机构", trigger: "blur" },
  ],
  platformAddress: [
    { required: true, message: "请输入平台地址", trigger: "blur" },
  ],
  contactPerson: [
    { required: false, message: "请输入联系人", trigger: "blur" },
  ],
  phone: [{ required: false, message: "请输入联系电话", trigger: "blur" }],
});

//更新查询数据
const handleUpdate = ({ key, value }) => {
  query[key] = value;
  if (!value) {
    get_sysPage();
  }
};
//查询
const handle_query = () => {
  get_sysPage();
};
//查询 - 重置
const handle_resetting = () => {
  query.platformName = "";
  get_sysPage();
};

//获取机构名称
const set_institution = (id) => {
  let obj = store.orgallData.find((item) => item.organizationid === id);
  if (!obj) {
    return "-";
  } else {
    return obj.name;
  }
};

//新建/编辑弹出框
const handle_drawer = (data) => {
  drawerVisible.value = true;
  if (!data) {
    //新建
    drawerTitle.value = "新建平台";
  } else {
    //编辑
    Object.assign(drawerform, data);
    drawerTitle.value = "平台编辑";
  }
  store.getOrgAll();
};

//新建/编辑弹出框--取消
const cancel_drawer = () => {
  Object.assign(drawerform, {
    contactPerson: "",
    organizationId: "",
    phone: "",
    pid: null,
    platformAddress: "",
    platformId: "",
    platformName: "",
    status: null,
  });
  drawerVisible.value = false;
};
//新建/编辑弹出框--确认
const confirm_drawer = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(
        `确定${drawerTitle.value}吗？`,
        `${drawerTitle.value}`,
        {
          type: "warning",
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }
      )
        .then(async () => {
          if (drawerTitle.value === "新建平台") {
            const res = await addSys({ ...drawerform });
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: res.msg,
              });
            } else {
              ElMessage({
                type: "error",
                message: res.msg,
              });
            }
          } else if (drawerTitle.value === "平台编辑") {
            const res = await updateSys({
              platformId: drawerform.platformId,
              platformName: drawerform.platformName,
              organizationId: drawerform.organizationId,
              contactPerson: drawerform.contactPerson,
              platformAddress: drawerform.platformAddress,
              phone: drawerform.phone,
            });
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: res.msg,
              });
            } else {
              ElMessage({
                type: "error",
                message: res.msg,
              });
            }
          }
          get_sysPage();
          formEl.resetFields();
          drawerVisible.value = false;
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};

//删除
const handle_del = async (id) => {
  ElMessageBox.confirm("确定删除该平台吗？", {
    type: "error",
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(async () => {
      const res = await deleteSys({
        platformId: id,
      });

      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: res.msg,
        });
        get_sysPage();
      } else {
        ElMessage({
          type: "error",
          message: res.msg,
        });
      }
    })
    .catch(() => {});
};

//分页
const handle_page = (currentPage, pageSize) => {
  page.value = currentPage;
  pagesize.value = pageSize;
  get_sysPage();
};

//获取平台数据
let time = ref(null);
const get_sysPage = async () => {
  loading.value = true;
  const res = await sysPage({
    page: page.value,
    pageSize: pagesize.value,
    platformName: query.platformName,
  });

  time.value = setTimeout(() => {
    loading.value = false;
  }, 5000);

  if (res.code === 200) {
    clearTimeout(time.value); // 清除定时器
    time.value = null;
    tableData.value = res.data.data;
    total.value = res.data.count;
    loading.value = false;
  }
};

onMounted(() => {
  get_sysPage();
});
</script>

<style lang="scss" scoped>
.platform {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;

  .top {
    width: 100%;
    padding: 10px;
    background: #fff;
    display: flex;
    flex-wrap: wrap;
    gap: 30px;

    > div {
      width: calc((100% - (6 - 1) * 30px) / 4);
      height: 40px;
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .cont {
    flex: 1;
    padding: 10px;
    background: #fff;

    display: flex;
    flex-direction: column;

    .cont_top {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .total_box {
        display: flex;

        > span {
          font-weight: bold;
          margin: 0 0.2px 0 0.05px;
        }

        p > span {
          margin: 0 0.05px;
          color: #09f;
        }
      }

      .operate {
        display: flex;
        gap: 10px;
      }
    }

    .cont_button {
      width: 100%;
      height: 40px;
      margin-top: 10px;
      display: flex;
      justify-content: end;
      align-items: center;
    }
  }
}

.el-table {
  .table_name {
    color: #09f;
    cursor: pointer;
  }

  .el-button {
    margin: 0 8px;
  }
}

.drawer_header {
  width: 100%;
  height: 60px;
  border-bottom: 1px solid #ccc;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;

  h3 {
    font-size: 20px;
    cursor: pointer;
  }
}

.drawer_cont {
  padding: 5px 15px;
  width: 100%;
  display: flex;
  flex-direction: column;

  .drawerForm {
    padding: 15px 0;
    // display: flex;
    // flex-wrap: wrap;
    // gap: 5px;
    // .el-form-item {
    //   width: calc(50% - 10px);
    //   width: 100%;
    // }
  }
}

.add_operate {
  display: flex;
  justify-content: end;
  gap: 10px;
}

.total > span {
  margin: 0 5px;
}

.el-button {
  margin: 0;
}
</style>
